﻿using Generic.Domain.Shared.Exception;
using Generic.Domain.Shared.Result;
using Generic.Domain.Shared.Const;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace Generic.App.HttpApi.Middleware
{
    /// <summary>
    /// 自定义异常中间件
    /// </summary>
    public class ExceptionMiddleware
    {
        /// <summary>
        /// 委托
        /// </summary>
        private readonly RequestDelegate _next;
        private readonly ILogger? _logger;

        public ExceptionMiddleware(RequestDelegate next, IApplicationBuilder app)
        {
            _next = next;
            _logger = (ILogger?)app.ApplicationServices.GetService(typeof(ILogger));
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (CustomFriendlyException ex)
            {
                await dealException(context, ex.Message);
                _logger?.LogException(ex);
            }
            catch (Exception ex)
            {
                await dealException(context, CommonErrorConst.CommonError);
                _logger?.LogException(ex);
            }

        }

        private async Task dealException(HttpContext context, string message)
        {
            context.Response.ContentType = "application/json";
            var result = new CustomResult
            {
                Code = ((int)CustomResultCode.系统异常).ToString(),
                Message = message
            };
            var stream = context.Response.Body;
            await JsonSerializer.SerializeAsync(stream, result, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });
        }

    }
}

